package com.yunchuang.controller.fileinfo;

import com.google.gson.Gson;
import com.yunchuang.model.dto.FileInfoQueryDto;
import com.yunchuang.utils.ProfileUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 获取文件列表
 *
 * @author ItJiange
 * @date 2023/10/23
 */
@WebServlet("/fileList")
public class FileInfoListController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            return;
        }
//        logger.info("获取文件列表...");
//        Socket socket = new Socket(ProfileUtils.getHost(), ProfileUtils.getPort());

        List<FileInfoQueryDto> fileList = listFiles();
        // 将集合转为 JSON 对象
        Gson gson = new Gson();
        String fileListJSON = gson.toJson(fileList);
        // 获取打印流
        PrintWriter writer = resp.getWriter();
        writer.write(fileListJSON);
        writer.flush();
        writer.close();
    }

    /**
     * 获取文件对象集合
     * @return
     */
    private List<FileInfoQueryDto> listFiles() {
        // 获取客户端存储文件目录
        String fileContext = ProfileUtils.getServerContext();
        // 获取所有文件对象
        File directory = new File(fileContext);
        File[] files = directory.listFiles();
        // 创建集合对象
        List<FileInfoQueryDto> fileInfoList = new LinkedList<>();
        // 遍历所有文件
        for (File file : files) {
            if (file.isFile()) {
                // 格式化时间
                Date date = new Date(file.lastModified());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 封装至文件对象
                FileInfoQueryDto fileInfoQueryDto = new FileInfoQueryDto();
                fileInfoQueryDto.setFileName(file.getName());
                fileInfoQueryDto.setFileCreateTime(sdf.format(date));
                fileInfoQueryDto.setFileLength(file.length() / 1024 + "KB");
                // 加入集合
                fileInfoList.add(fileInfoQueryDto);
            }
        }
        return fileInfoList;
    }
}
